#include<iostream>
#include<etcd/Client.hpp>
#include<etcd/KeepAlive.hpp>
#include<etcd/Response.hpp>
#include<etcd/Watcher.hpp>
#include<etcd/Value.hpp>
void callback(etcd::Response resp)
{
    if(resp.is_ok()==false)
    {
        cout<<"收到一个错误事件通知"<<resp.error_message()<<std::endl;
        return;
    }
    for(auto ev:resp.events())
    {
        if(ev.event_type()==etcd::Event::EventType::PUT)
        {
            std::cout<<"服务信息发生了变化\n";
            std::cout<<"原来的值: "<<ev.prev_kv().key()<<"-"<<ev.prev_kv().as_string()<<std::endl;
            std::cout<<"现在的值: "<<ev.kv().key()<<"-"<<ev.kv().as_string()<<std::endl;
        }
        else if(ev.event_type()==etcd::Event::EventType::DELETE_)
        {
            std::cout<<ev.prev_kv().key()<<"-"<<ev.prev_kv().as_string()<<"服务信息被删除\n";
        }
    }
}
int main()
{
    std::string etcd_host = "http://127.0.0.1:2379";
    //实例化客户端对象
    etcd::Client client(etcd_host);
    //获取“/service”键值的value的异步结果对象
    auto resp = client.ls("/service").get();
    if(resp.is_ok()==false)
    {
        std::cout<<"获取数据失败"<<resp.error_message()<<std::endl;
        return -1;
    }
    size_t sz = resp.keys().size();
    //打印键值包含的对象（可以有多个）
    for(int i =0;i<sz;i++)
        std::cout<<resp.value(i).as_string()<<"可以提供"<<resp.key(i)<<"服务\n";
    etcd::Watcher watcher(client,"/service",callback,true);
    watcher.Wait();
}